import axios from 'axios'
import QS from 'qs'

axios.defaults.withCredentials = true
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/x-www=form-urlencoded'

// const baseUrl = 'http://127.0.0.1:80/'

export function get (url, params) {
  return new Promise((resolve, reject) => {
    axios.get(url, {params: params})
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err)
      })
  })
}

/**
 * post方法，对应post请求
 * @param {String} url [请求的url地址]
 * @param {Object} params [请求时携带的参数]
 */
export function post (url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, QS.stringify(params))
      .then(res => {
        resolve(res.data)
      })
      .catch(err => {
        reject(err.data)
      })
  })
}

/*

export default {
  requestGet (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.get(baseUrl + url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  requestQuickGet (url) {
    return new Promise((resolve, reject) => {
      axios.get(baseUrl + url).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  requestPost (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(baseUrl + url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  requestPostForm (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.post(baseUrl + url, params, {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }).then(res => {
        resolve(res.data)// 注意res是axios封装的对象，res.data才是服务端返回的信息
      }).catch(error => {
        reject(error)
      })
    })
  },
  requestPut (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.put(baseUrl + url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  },
  requestDelete (url, params = {}) {
    return new Promise((resolve, reject) => {
      axios.delete(baseUrl + url, params).then(res => {
        resolve(res.data)
      }).catch(error => {
        reject(error)
      })
    })
  }
}
*/
